import time
import requests
import json
from datetime import datetime
from openai import OpenAI
# 使用的模型为qwen2.5  32B  一次判断一条记录 GPU消耗是90% 功耗 280W

def get_chat_completion(api_key, base_url, model, user_content):
   """
   获取聊天模型的完成结果。

   :param api_key: OpenAI API Key
   :param base_url: API的基础URL
   :param model: 使用的模型名称
   :param user_content: 用户发送的消息内容
   :return: None
   """
   try:
       client = OpenAI(
           api_key=api_key,
           base_url=base_url,
       )

       messages = [
           {'role': 'system', 'content': '你作为一个数据核查人员 输入的数据中如果有 发送数据给NCC  这的关键词打印YES  如果没有就打印NO'},
           {'role': 'user', 'content': user_content}
       ]

       completion = client.chat.completions.create(
           model=model,
           messages=messages
       )
   except Exception as e:
       print(f"错误信息：{e}")
       print("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
   return completion.choices[0].message.content    

class DataChecker:
    def __init__(self, url, model):
        self.url = url
        self.model = model

    def send_request(self, content):
        ai_content =""
        """
        向指定的API发送POST请求，并检查返回的消息中是否包含特定关键词。

        :param content: 用户输入的内容
        """
        data = {
            "model": self.model,
            "messages": [
                {
                    "role": "system",
                    "content": "你作为一个数据核查人员 输入的数据中如果有 发送数据给NCC  这的关键词打印全部数据数据 如果没有就打印NO "
                },
                {
                    "role": "user",
                    "content": content
                }
            ],
            "stream": False
        }

        try:
            response = requests.post(self.url, json=data)
            if response.status_code == 200:
                response_data = response.json()
                if 'message' in response_data and 'content' in response_data['message']:
                    ai_content  = response_data['message']['content']
                    # print(ai_content)
                    return ai_content 
                else:
                    print("响应数据中没有找到content字段")
            else:
                print(f"请求失败，状态码: {response.status_code}")
                return {response.status_code}
        except Exception as e:
            print(f"发生错误: {e}")
        return  ai_content    

    def read_and_process_file(self, file_path):
        """
        读取文件内容，每次处理10行内容，然后等待1秒钟。

        :param file_path: 文件的路径
        """
        start_time1 = datetime.now()
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            total_lines = len(lines)

            for i in range(0, total_lines, 10):
                for line in lines[i:i + 10]:
                    start_time = datetime.now()
                    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
                    print(f"{current_time}|发送数据给AI|"+line.strip())
                    # 开始发送数据给AI做判断
                    #ai_content=self.send_request(line.strip())
                    ai_data = get_chat_completion(api_key="sk-096ec5c5cb6e40d196a3ed086965e025",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",model="qwen-plus",user_content=line.strip())
                    end_time = datetime.now()
                    elapsed_time = (end_time - start_time).total_seconds()
                    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 
                    print(f"{current_time}|AI返回数据|{ai_data}")
                    print(f"{current_time}|该次处理总耗时: {elapsed_time:.2f} 秒")
                    print("\n\n")
                time.sleep(1)

        end_time1 = datetime.now()          
        elapsed_time = (end_time1 - start_time1).total_seconds() 
        print(f"{current_time}|全部业务处理总耗时: {elapsed_time:.2f} 秒")

# 使用示例
if __name__ == "__main__":
    url = "http://172.16.1.203:11434/api/chat"
    model = "qwen2.5:7b"
    file_path = 'testdata.txt'

    checker = DataChecker(url, model)
    checker.read_and_process_file(file_path)
